/****************************************************
          File Name:48-1-reader.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 07:48:59 PM CST
*****************************************************/

#include "svshm_xfr.h"

int
main(int argc, char *argv[])
{
    int semid, fd;
	void *addr;
	
	semid=semget(SEM_KEY,0,0);		// get semaphore
	if(semid==-1)
		err("semget");

	/**********  fd  ************/
	if((fd=open(PATH,O_RDWR,00644))==-1)
		err("open/creat file");
	/***********	end		************/
	
	addr=mmap(NULL,LEN, PROT_READ,MAP_SHARED,fd,0);
	if(addr == MAP_FAILED)
		err("mmap");
    
    close(fd);
    remove(PATH); // this line can be put anywhere behind mmap() call
    for (;;)
    {
		if(reserve(semid,READ_SEM)==-1)
			if(errno==EIDRM)		/* semaphore has been removed by writer */
				break;
			else
				err("reserve");

/* by adding 'memset' to clean the underlying file in writer program the following
 * operation will not cause problem 
 */
        if (write(STDOUT_FILENO, addr, LEN) != LEN)
            err("partial/failed write");
		
		if(release(semid,WRITE_SEM)==-1)
			err("release");
    }
	
	if(release(semid,WRITE_SEM)==-1)
		if(errno!=EINVAL)				/* semaphore no longer exist */
			err("release");
	
	if(munmap(addr,LEN)==-1)
		err("munmap");
	
    exit(EXIT_SUCCESS);
}
